/*
 * Indiana University Community Grid Computing Lab Software License,Version 1.1
 *
 * Copyright (c) 2002 Community Grid Computing Lab, Indiana University.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *      "This product includes software developed by the Indiana University
 *       Community Grid Computing Lab (http://www.communitygrids.iu.edu/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Indiana Univeristy","Indiana Univeristy Pervasive Techonology
 *    Labs" and  "Indiana Univeristy Community Grid Computing Lab" must not be
 *    used to endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    http://www.communitygrids.iu.edu/.
 *
 * 5. Products derived from this software may not use "Indiana
 *    University" name nor may "Indiana University" appear in their name,
 *    without prior written permission of the Indiana University.
 *
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * INDIANA UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package cgl.sensorgrid.sopac.gps.threadpool;

import java.util.*;

/**
 * Java Thread Pool
 *
 * This is a thread pool that for Java, it is
 * simple to use and gets the job done. This program and
 * all supporting files are distributed under the Limited
 * GNU Public License (LGPL, http://www.gnu.org).
 *
 * This is the main class for the thread pool. You should
 * create an instance of this class and assign tasks to it.
 *
 * For more information visit http://www.jeffheaton.com.
 *
 * @author Jeff Heaton (http://www.jeffheaton.com)
 * @version 1.0
 */
public class ThreadPool {
    /**
     * The threads in the pool.
     */
    protected Thread threads[] = null;
    /**
     * The backlog of assignments, which are waiting
     * for the thread pool.
     */
    Collection assignments = new ArrayList(3);
    /**
     * A Done object that is used to track when the
     * thread pool is done, that is has no more work
     * to perform.
     */
    protected Done done = new Done();

    /**
     * The constructor.
     *
     * @param size  How many threads in the thread pool.
     */
    public ThreadPool(int size) {
        threads = new WorkerThread[size];
        for (int i = 0; i < threads.length; i++) {
//            System.out.println("starting thread " + i);
            threads[i] = new WorkerThread(this);
            threads[i].start();
        }
    }

    /**
     * Add a task to the thread pool. Any class
     * which implements the Runnable interface
     * may be assigned. When this task runs, its
     * run method will be called.
     *
     * @param r   An object that implements the Runnable interface
     */
    public synchronized void assign(Runnable r) {
        done.workerBegin();
        assignments.add(r);
        notify();
    }

    /**
     * Get a new work assignment.
     *
     * @return A new assignment
     */
    public synchronized Runnable getAssignment() {
        try {
            while (!assignments.iterator().hasNext()) {
                wait();
            }

            Runnable r = (Runnable) assignments.iterator().next();
            assignments.remove(r);
            return r;
        } catch (InterruptedException e) {
            done.workerEnd();
            return null;
        }
    }

    /**
     * Called to block the current thread until
     * the thread pool has no more work.
     */
    public void complete() {
        done.waitBegin();
        done.waitDone();
    }


    protected void finalize() {
        done.reset();
        for (int i = 0; i < threads.length; i++) {
            threads[i].interrupt();
            done.workerBegin();
            threads[i].destroy();
        }
        done.waitDone();
    }
}


/**
 * The worker threads that make up the thread pool.
 *
 * @author Jeff Heaton
 * @version 1.0
 */
class WorkerThread extends Thread {

    private static int threadCount = 0;
    /**
     * True if this thread is currently processing.
     */
    public boolean busy;
    /**
     * The thread pool that this object belongs to.
     */
    public ThreadPool owner;
    private int id;
    /**
     * The constructor.
     *
     * @param o the thread pool
     */
    WorkerThread(ThreadPool o) {
        threadCount++;
        id = threadCount;
//        System.out.println("Thread Count " + threadCount);
        owner = o;
    }

    /**
     * Scan for and execute tasks.
     */
    public void run() {
        Runnable target = null;
        do {
            target = owner.getAssignment();
            if (target != null) {
                target.run();
                owner.done.workerEnd();
//               System.out.println(id +  " complete...");
               //threadCount--;
            }
        } while (target != null);
        if(target==null){
            System.out.println("target null");
        }
    }
}
